package com.study.javassist;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

public class Demo {
    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass targetClass = pool.get("com.study.javassist.TargetClass");
        CtMethod targetMethod = targetClass.getDeclaredMethod("execute");


        targetMethod.instrument(new ExprEditor() {
            @Override
            public void edit(MethodCall m) throws CannotCompileException {
                m.replace("System.out.println(\"Before method call: \" + $1); $_ = $proceed($$);");
            }
        });
/*        // 在方法调用前记录开始时间
        targetMethod.addLocalVariable("startTime",CtClass.longType);
        targetMethod.insertBefore("startTime = System.currentTimeMillis();");

        // 在方法调用后计算耗时并输出
        targetMethod.insertAfter("System.out.println(\"Execution time: \" + (System.currentTimeMillis() - startTime) + \" ms\");");
        // 转换并加载修改后的类
        Class<?> modifiedClass = targetClass.toClass();
        targetClass.detach();

        // 创建目标类实例并调用方法
        Object instance = modifiedClass.newInstance();
        modifiedClass.getMethod("execute").invoke(instance);*/
    }
}
